#!/usr/bin/env python
# $Id$

from page import page
import sys, urllib
import db 

class add(page):

	def __init__(self):
		page.__init__(self)
		self.headingstr = "Select Type"
		self.db1 = db.db()
		self.upcdb1 = db.upcdb()

	def get_var(self, var, default=""):
		if request.has_key(var):
			return request[var][0]
		else:
			return default

	def render(self):
		self.logic()
		self.encoding()
		self.html()

	def add_type_and_upc(self):
		upc = request["upc"][0]
		date = request["date"][0]
		amt = request["amt"][0]
		amt, unit = amt.split()
		typeid = request["typeid"][0]
		desc = request["desc"][0].replace("'", "")
		if request.has_key("count"):
			count = request["count"][0]
			cmes = "%s times" % count
		else:
			count = 1
			cmes = "1 time"
		if not self.db1.upc_type_there(upc):
			self.db1.add_upc_type(upc, typeid, amt, unit, desc)
		self.log("added %s to upc_types" % typeid)
		for num in range(int(count)):
			self.db1.add_upc(upc, date)
		self.log("added %s to upcs %s" % (upc, cmes))

	def logic(self):
		if request.has_key("cancel"):
			raise HTTP_REDIRECTION, "menu.py"
		if request.has_key("submit"):
			self.add_type_and_upc()
			raise HTTP_REDIRECTION, "add_items.py?%s" % urllib.urlencode({"m":"%s containers of '%s' have been added to your foodstorage." % (request["count"][0], request["desc"][0])})

	def form(self):
		form = """
		<form name="add" method="GET" action="select_type.py">
		<input type=hidden name=upc value=%s>
		<input type=hidden name=date value=%s>
		<input type=hidden name=count value=%s>
		<table style="text-align: left; width: 20%%;" border="0" cellpadding="2" cellspacing="2">
		<tbody>
		<tr>
			<td>Type</td>
			<td>""" % (request["upc"][0], request["date"][0], self.get_var("count", 1)) 
		print form
		print "<select name=typeid>"
		types = self.db1.get_type_list()
		for type in types:
			id, desc = type
			print "\t<option value=%s>%s</option>" % (id, desc)
		print "</select>"
		form = """</td>
		</tr>
		<tr>
			<td>Description</td>
			<td><input type=text name=desc value="%s"></td>
		</tr>
		<tr>
			<td>Amount and Unit</td>
			<td><input type=text name=amt value="%s"></td>
		</tr>
		<tr>
			<td><input name=submit type=submit value="Submit"></td>
			<td><input type=submit name=cancel value="Menu"></td>
		</tr>
		<script>document.forms.add.typeid.focus();</script>
		</tbody>
		</table>
		</form>
		""" % (self.get_var("desc"), self.get_var("amt"))
		print form

	def body(self):
		self.start_body()
		self.heading()
		self.form()
		self.footer()
		self.end_body()

class runner:
	def _test(self):
		add().render()

	def _doctest(self):
		import doctest
		doctest.testmod()

if __name__ == "__main__":
	r = runner()
	getattr(r, "_"+sys.argv[1])()
else:
	add().render()
